﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using System.Threading;
using ESRI.ArcGIS.Carto;
using ESRI.ArcGIS.Controls;
using ESRI.ArcGIS.SystemUI;
using ESRI.ArcGIS.Geodatabase;
using ESRI.ArcGIS.Geometry;

namespace Tayninh2011
{
    public sealed partial class FrmMap : RootForm
    {
        private IToolbarMenu ContexMenuTOC = new ToolbarMenuClass();

        //private FrmMain frmMain = FrmMain.FormMain;
        private ICommand cmdSelectFeature = new ControlsSelectFeaturesToolClass();
        private ICommand cmdPan = new ControlsMapZoomPanToolClass();

        private string dieuKienLocThua = "";

        public string DieuKienLocThua
        {
            get { return dieuKienLocThua; }
            set { dieuKienLocThua = value; }
        }

        private string[] _strLayerNames = { "tn_duong", "tn_hem", "tn_thua" };

        public string[] StrLayerNames
        {
            get { return _strLayerNames; }
            set { _strLayerNames = value; }
        }

        //private const int CP_NOCLOSE_BUTTON = 0x200;
        //protected override CreateParams CreateParams
        //{
        //    get
        //    {
        //        CreateParams myCp = base.CreateParams;
        //        myCp.ClassStyle = myCp.ClassStyle | CP_NOCLOSE_BUTTON;
        //        return myCp;
        //    }
        //} 

        //dam bao window la singleton
        private static bool isShown = false;
        private static readonly FrmMap frmMap = new FrmMap();
        //delegate for load form
        public delegate void delegAddLayerAuto(string[] layers);
        public delegAddLayerAuto AddLayerAutoDel;
        //thread add layer
        private Thread threadAddLayer;



        private FrmMap()
        {
            InitializeComponent();
            this.ControlBox = false;
            AddLayerAutoDel = new delegAddLayerAuto(addLayerAuto);
            
            //this.MdiParent = frmMain;
        }

        public static FrmMap FormMap
        {
            get { return frmMap; }
        }
        public new void Show()
        {
            if (isShown)
            {
                base.Show();
                base.Focus();
                //base.WindowState = FormWindowState.Maximized;
            }
            else
            {
                base.Show();
                base.Focus();
                //base.WindowState = FormWindowState.Maximized;
                isShown = true;
            }
        }
        static FrmMap()
        {
            FormMap.FormClosing += new FormClosingEventHandler(frmMap_FormClosing);
        }
        private static void frmMap_FormClosing(object sender, FormClosingEventArgs e)
        {
            e.Cancel = true;
            isShown = false;
            FormMap.Hide();
        }

        private void FrmMap_Load(object sender, EventArgs e)
        {
            
            //cmdSelectFeature.OnCreate(axMapControl1.Object);
            //axMapControl1.CurrentTool = (ITool)cmdSelectFeature;
            
            cmdPan.OnCreate(axMapControl1.Object);
            //this.axToolbarControl1.Visible = false;
            //this.axToolbarControl1.Visible = true;
            string[] res = GetType().Assembly.GetManifestResourceNames();
            //MessageBox.Show(res[2]);
            //cmdPan.Bitmap=System.Drawing.Bitmap(GetType(assembly
            ContexMenuTOC.AddItem("esriControls.ControlsPageZoomInFixedCommand", 1, 0, false, esriCommandStyles.esriCommandStyleIconAndText);
            ContexMenuTOC.AddItem("esriControls.ControlsPageZoomOutFixedCommand", 2, 0, false, esriCommandStyles.esriCommandStyleIconAndText);
            ContexMenuTOC.AddItem("esriControls.ControlsPageZoomWholePageCommand", -1, -1, false, esriCommandStyles.esriCommandStyleIconAndText);
            ContexMenuTOC.AddItem("esriControls.ControlsPageZoomPageToLastExtentBackCommand", -1, -1, false, esriCommandStyles.esriCommandStyleIconAndText);
            ContexMenuTOC.AddItem("esriControls.ControlsPageZoomPageToLastExtentForwardCommand", -1, -1, false, esriCommandStyles.esriCommandStyleIconAndText);
            ContexMenuTOC.AddItem("esriControls.ControlsMapZoomInTool", 3, 0, true, esriCommandStyles.esriCommandStyleIconAndText);
            ContexMenuTOC.AddSubMenu("esriControls.ControlsFeatureSelectionMenu", 2, true);
            //menu.AddItem("tui", 1, 1, true, esriCommandStyles.esriCommandStyleIconAndText);
            ContexMenuTOC.SetHook(axMapControl1);
            //addLayerAuto(_strLayerNames);
            //threadAddLayer = new Thread(new ThreadStart(funcThreadAddLayer));
            //threadAddLayer.Start();
        }
        private void startAddLayers()
        {
            AddLayerAutoDel(this.StrLayerNames);
        }

        private void axTocControl1_onmousedown(object sender, ESRI.ArcGIS.Controls.ITOCControlEvents_OnMouseDownEvent e)
        {
            IBasicMap map = null;
            ILayer layer = null;
            object obj = null;
            object index = null;
            esriTOCControlItem item = esriTOCControlItem.esriTOCControlItemNone;

            if (e.button == 2)
            {
                //MessageBox.Show("hi");
                axTOCControl1.HitTest(e.x, e.y, ref item, ref map, ref layer, ref obj, ref index);

                //ContexMenuTOC.PopupMenu(e.x, e.y, axTOCControl1.hWnd);

                //menu.AddItem("esriControls.ControlsPageZoomWholePageCommand", -1, -1, false, esriCommandStyles.esriCommandStyleIconAndText);
                //menu.AddItem("esriControls.ControlsPageZoomPageToLastExtentBackCommand", -1, -1, true, esriCommandStyles.esriCommandStyleIconAndText);
                //menu.AddItem("esriControls.ControlsPageZoomPageToLastExtentForwardCommand", -1, -1, false, esriCommandStyles.esriCommandStyleIconAndText);

            }
        }
        private void addLayerAuto(string [] layers)
        {
            ITnToolsWorkspace workspaceTool = new TnTools();
            IFeatureClass fc;
            IFeatureLayer fl;
            for (int i = 0; i < this._strLayerNames.Length; i++)
            {
                fc = workspaceTool.OpenFeatureClassFromSDE(RootForm._sdeWorkspace, this._strLayerNames[i]);
                fl = new FeatureLayerClass();
                fl.FeatureClass = fc;
                ILayer layer = (ILayer)fl;
                layer.Name = fc.AliasName;
                axMapControl1.AddLayer(layer);
            }
            
            axMapControl1.Map.Name = "Các lớp bản đồ";
            axMapControl1.ActiveView.Refresh();
            axTOCControl1.SetBuddyControl(axMapControl1);
            axTOCControl1.Update();
            axTOCControl1.Refresh();
        }
        private void funcThreadAddLayer()
        {
            TnThreadClassFrmMap adVanceThreadClassObject = new TnThreadClassFrmMap(this);
            adVanceThreadClassObject.Run(AddLayerAutoDel,this._strLayerNames);
        }

        private void axMapControl1_OnMouseDown(object sender, IMapControlEvents2_OnMouseDownEvent e)
        {
            if (e.button == 1)
            {
                
                //axMapControl1.CurrentTool = (ITool)cmdSelectFeature;
            }
            else if (e.button == 2)
            {
                
                axMapControl1.CurrentTool = (ITool)cmdPan;
                
                
            }
        }

        private void axToolbarControl1_ControlAdded(object sender, ControlEventArgs e)
        {
            
        }

        private void button1_Click(object sender, EventArgs e)
        {
            Form2 frm2 = new Form2();
            frm2.Show();
        }

        private void FrmMap_Shown(object sender, EventArgs e)
        {
            this.axToolbarControl1.Refresh();
        }

        //zoom den thua duoc chon theo DieuKienLocThua
        public void ZoomToSelected(string table, string dieukien)
        {
            this.Show();
            IMap map = null;
            ILayer layer = null;
            IFeatureLayer featureLayer = null;
            IFeatureSelection featureSelection = null;
            IQueryFilter queryFilter = new QueryFilterClass();
            map = axMapControl1.Map;
            //MessageBox.Show(map.LayerCount.ToString());
            for (int i = 0; i < map.LayerCount; i++)
            {
                //MessageBox.Show(map.LayerCount.ToString());
                layer = map.get_Layer(i);
                
                if (layer.Name == table)
                {
                    //MessageBox.Show(layer.Name);
                    break;
                }
            }
            featureLayer = (IFeatureLayer)layer;
            featureSelection = (IFeatureSelection)featureLayer;
            queryFilter.WhereClause = dieukien;
            axMapControl1.ActiveView.PartialRefresh(esriViewDrawPhase.esriViewGeoSelection, null, null);
            featureSelection.SelectFeatures(queryFilter, esriSelectionResultEnum.esriSelectionResultNew, false);

            IFeature feature = null;
            IEnvelope envelope = new EnvelopeClass();
            IEnvelope curExtent = null ;
            IEnvelope prevExtent = null;
            IArea area = null;
            IEnumFeature numFeature = null;

            axMapControl1.Extent = axMapControl1.FullExtent;
            numFeature = (IEnumFeature)axMapControl1.ActiveView.FocusMap.FeatureSelection;
            feature = numFeature.Next();
            envelope = feature.Shape.Envelope.Envelope;

            if (feature.Shape.GeometryType == esriGeometryType.esriGeometryPoint || envelope.Width == 0 && envelope.Height == 0)
            {
                if (axMapControl1.ActiveView.FocusMap.ReferenceScale != 0.0)
                {
                    axMapControl1.ActiveView.FocusMap.MapScale = axMapControl1.ActiveView.FocusMap.ReferenceScale / 2;
                    envelope = axMapControl1.ActiveView.Extent;
                    area = (IArea)feature.Shape.Envelope;
                    envelope.CenterAt(area.Centroid);
                }
                else
                {
                    envelope = axMapControl1.ActiveView.Extent;
                    area = (IArea)feature.Shape.Envelope;
                    envelope.CenterAt(area.Centroid);
                    envelope.Expand(0.2, 0.2, true);
                }
                axMapControl1.ActiveView.Extent = envelope;
                axMapControl1.ActiveView.Refresh();
            }
            else
            {
                axMapControl1.ActiveView.Extent = feature.Extent;
                axMapControl1.ActiveView.Refresh();
            }


        }

        private void btnClose_Click(object sender, EventArgs e)
        {
            this.Hide();
        }
    }
}
